// pages/market/market.js
const stockAPI = require('../../utils/stockApi');

Page({
  /**
   * 页面的初始数据
   */
  data: {
    stockList: [],
    loading: true,
    searchKeyword: '',
    refreshing: false,
    currentRankingTab: 'rise',
    rankingList: [],
    dragonTigerList: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log('行情页面加载完成');
    this.loadInitialData();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 页面显示时刷新数据
    if (this.data.rankingList.length > 0) {
      this.refreshRankingData();
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉刷新
   */
  onPullDownRefresh() {
    if (this.data.searchKeyword) {
      this.refreshStockData().then(() => {
        wx.stopPullDownRefresh();
      });
    } else {
      this.refreshRankingData().then(() => {
        wx.stopPullDownRefresh();
      });
    }
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  /**
   * 加载初始数据
   */
  async loadInitialData() {
    try {
      this.setData({ loading: true });

      // 并行加载排行榜和龙虎榜数据
      const [rankingResult, dragonTigerResult] = await Promise.all([
        stockAPI.getRiseRanking(),
        stockAPI.getDragonTigerList()
      ]);

      if (rankingResult.success && dragonTigerResult.success) {
        this.setData({
          rankingList: rankingResult.data,
          dragonTigerList: dragonTigerResult.data,
          loading: false
        });
      } else {
        throw new Error('加载数据失败');
      }
    } catch (error) {
      console.error('加载初始数据失败:', error);
      this.setData({ loading: false });
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
    }
  },

  /**
   * 切换排行榜标签
   */
  async switchRankingTab(e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({
      currentRankingTab: tab,
      loading: true
    });

    try {
      let result;
      switch (tab) {
        case 'rise':
          result = await stockAPI.getRiseRanking();
          break;
        case 'fall':
          result = await stockAPI.getFallRanking();
          break;
        case 'volume':
          result = await stockAPI.getVolumeRanking();
          break;
        case 'turnover':
          result = await stockAPI.getTurnoverRanking();
          break;
        default:
          result = await stockAPI.getRiseRanking();
      }

      if (result.success) {
        this.setData({
          rankingList: result.data,
          loading: false
        });
      } else {
        throw new Error(result.error);
      }
    } catch (error) {
      console.error('切换排行榜失败:', error);
      this.setData({ loading: false });
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
    }
  },

  /**
   * 刷新排行榜数据
   */
  async refreshRankingData() {
    try {
      this.setData({ refreshing: true });

      const [rankingResult, dragonTigerResult] = await Promise.all([
        this.getCurrentRankingData(),
        stockAPI.getDragonTigerList()
      ]);

      if (rankingResult.success && dragonTigerResult.success) {
        this.setData({
          rankingList: rankingResult.data,
          dragonTigerList: dragonTigerResult.data,
          refreshing: false
        });
      } else {
        throw new Error('刷新数据失败');
      }
    } catch (error) {
      console.error('刷新数据失败:', error);
      this.setData({ refreshing: false });
      wx.showToast({
        title: '刷新失败',
        icon: 'none'
      });
    }
  },

  /**
   * 获取当前排行榜数据
   */
  async getCurrentRankingData() {
    const tab = this.data.currentRankingTab;
    switch (tab) {
      case 'rise':
        return await stockAPI.getRiseRanking();
      case 'fall':
        return await stockAPI.getFallRanking();
      case 'volume':
        return await stockAPI.getVolumeRanking();
      case 'turnover':
        return await stockAPI.getTurnoverRanking();
      default:
        return await stockAPI.getRiseRanking();
    }
  },

  /**
   * 刷新搜索结果数据
   */
  async refreshStockData() {
    try {
      this.setData({ refreshing: true });

      const codes = this.data.stockList.map(stock => stock.code);
      const result = await stockAPI.getBatchStockData(codes);

      if (result.success) {
        this.setData({
          stockList: result.data,
          refreshing: false
        });
      } else {
        throw new Error(result.error);
      }
    } catch (error) {
      console.error('刷新股票数据失败:', error);
      this.setData({ refreshing: false });
      wx.showToast({
        title: '刷新失败',
        icon: 'none'
      });
    }
  },

  /**
   * 搜索股票
   */
  async onSearchInput(e) {
    const keyword = e.detail.value;
    this.setData({ searchKeyword: keyword });

    if (keyword.trim()) {
      try {
        const result = await stockAPI.searchStock(keyword);
        if (result.success) {
          // 获取搜索结果的详细数据
          const codes = result.data.map(item => item.code);
          const detailResult = await stockAPI.getBatchStockData(codes);

          if (detailResult.success) {
            this.setData({ stockList: detailResult.data });
          }
        }
      } catch (error) {
        console.error('搜索失败:', error);
      }
    } else {
      // 清空搜索时清空搜索结果
      this.setData({ stockList: [] });
    }
  },

  /**
   * 点击股票项跳转详情
   */
  onStockItemTap(e) {
    const stock = e.currentTarget.dataset.stock;
    wx.navigateTo({
      url: `/pages/stockDetail/stockDetail?code=${stock.code}&name=${stock.name}`
    });
  }
});
